package com.binvshe.binvshe.message.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.app.home.ClassEvent;
import com.binvshe.binvshe.app.home.CommentActivity;
import com.binvshe.binvshe.common.image.IML;
import com.binvshe.binvshe.message.MessageType;
import com.binvshe.binvshe.message.dao.Message;
import com.binvshe.binvshe.message.dao.MessageHelper;
import com.binvshe.binvshe.opus.OpusDetailsNewAcitvity;
import com.pachong.android.baseuicomponent.CompState;
import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.baseuicomponent.fragment.SwipeListFragment;
import com.pachong.android.frameworkbase.dialog.AlertDialogFragment;
import com.pachong.android.frameworkbase.utils.DateTimeUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * A simple {@link Fragment} subclass.
 */
public class LikeMessageFragment extends SwipeListFragment {

    @Override
    public RecyclerViewBaseAdapter createAdapter() {
        return new LikeMessageListAdapter(getContext());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        setPullToRefreshEnable(false);
        setAutoLoading(false);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        reload();
    }

    void reload() {
        getAdapter().getData().clear();
        getAdapter().notifyDataSetChanged();
        startLoading();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onStartRefreshing() {
        super.onStartRefreshing();
        startLoading();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventRefresh(ClassEvent.RefreshEvent refreshEvent) {
        getMessageData();
    }

    @Override
    public void onStartLoading() {
        getMessageData();
    }

    public void getMessageData() {
        List<Message> messageList = MessageHelper.getInstance().loadMessage(MessageType.MSG_TYPE_LIKE_ARTICAL, MessageType.MSG_TYPE_LIKE_COMMENT);
        if (messageList.size() <= 0) {
            setState(CompState.EMPTY);
        } else {
            setState(CompState.DATA);
            getAdapter().getData().clear();
            getAdapter().getData().addAll(messageList);
            getAdapter().notifyDataSetChanged();
        }
    }


    @Override
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int position, long itemId) {

        final AlertDialogFragment dialogFragment = new AlertDialogFragment();
        dialogFragment.setTitle("删除消息")
                .setMessage("确定删除？")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Message msg = (Message) getData().get(position);
                        MessageHelper.getInstance().getMsgDao().delete(msg);
                        reload();
                        dialogFragment.dismissAllowingStateLoss();
                    }
                })
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialogFragment.dismissAllowingStateLoss();
                    }
                }).show(getFragmentManager());

        return true;
    }



    public class LikeMessageListAdapter extends RecyclerViewBaseAdapter<Message> {

        public LikeMessageListAdapter(Context con) {
            super(con);
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            return new VH(setAdapterViewItem(parent, R.layout.item_like_message));
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder holder, final int position) {
            final VH viewHolder = (VH) holder;
            final Message message = getData().get(position);
            if (!TextUtils.isEmpty(message.getIcon()))
                IML.load(getContext(), viewHolder.mImgHead, message.getIcon());
            if (!TextUtils.isEmpty(message.getTitle())) {
                viewHolder.mTvTitle.setText(message.getTitle());
            }
            try {
                long dateInMills = Long.parseLong(message.getDate());
                String dateStr = DateTimeUtil.getDateTimeStr(new Date(dateInMills));
                viewHolder.tvDate.setVisibility(View.VISIBLE);
                viewHolder.tvDate.setText(dateStr);

            } catch (NumberFormatException e) {

            }

            if (message.getIsRead()) {
                viewHolder.mImgPoint.setVisibility(View.GONE);
            } else {
                viewHolder.mImgPoint.setVisibility(View.VISIBLE);
            }
            String messageExtra = message.getExtra();
            try {
                JSONObject extraJobj = new JSONObject(messageExtra);
                final int original_article_id = extraJobj.optInt("original_article_id");
//                final int original_comment_id = extraJobj.optInt("original_comment_id");
                if (message.getType() == MessageType.MSG_TYPE_LIKE_ARTICAL) {
                    if (!TextUtils.isEmpty(message.getExtra()))
                        viewHolder.mTvComment.setText("点赞了我作品:" + message.getContent());
                    setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            setIsReadView(getData().get(position));
                            notifyDataSetChanged();
                            OpusDetailsNewAcitvity.start(getContext(), original_article_id);
                        }
                    });
                } else if (message.getType() == MessageType.MSG_TYPE_LIKE_COMMENT) {
                    if (!TextUtils.isEmpty(message.getExtra()))
                        viewHolder.mTvComment.setText("点赞了我评论:" + message.getContent());
                    setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            setIsReadView(getData().get(position));
                            notifyDataSetChanged();
                            CommentActivity.start(getActivity(), original_article_id, false);
                        }
                    });
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        private void setIsReadView(Message message) {
            message.setIsRead(true);
            MessageHelper.getInstance().updataIsRead(message);
        }

        public class VH extends RecyclerView.ViewHolder {

            @Bind(R.id.mImgHead)
            CircleImageView mImgHead;
            @Bind(R.id.mTvTitle)
            TextView mTvTitle;
            @Bind(R.id.mTvComment)
            TextView mTvComment;
            @Bind(R.id.mImgPoint)
            ImageView mImgPoint;
            @Bind(R.id.tvDate)
            TextView tvDate;

            public VH(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }
}
